import * as usersService from '../services/usersList'

export default {
	namespace: 'usersList',

	state: {
		list: [],
		pageState: {
			page: 1,
			pageSize: 10,
			total: null,
		},
	},

	reducers: {
		save ( state, { payload: { data: list, pageState } }) {
			return { ...state, list, pageState }
		},
	},

	effects: {
		*fetch ({ payload: { pageParams = {} } }, { call, put }) {
			// 1. 分页默认值 处理入参
			const { page = 1, pageSize = 10 } = pageParams
			const pageIn = { _page: page, _limit: pageSize }  //请求传入的参数对象
			// 2.请求表格数据并赋值
			const { data, pageOut } = yield call(usersService.queryList, pageIn)
			const pageState = { page , pageSize, total:pageOut.total } //state中管理的分页对象
			yield put({ type: 'save', payload: { data, pageState } })
		},
		
		// 删除
		*remove ({ payload: id }, { call, put }) {
			yield call(usersService.remove, id)
			yield put({ type: 'reload'})
		},

		// 修改
		*patch ({ payload: { id, values } }, { call, put }) {
			yield call(usersService.patch, id, values)
			yield put({ type: 'reload' })
		},
		 // 重载
		*reload (action, { put, select }){
			// 用select获取state
			const { page, pageSize } = yield select(_ => _.usersList.pageState)
			yield put({ type: 'fetch', payload: { pageParams: { page, pageSize } } })
		},
	},

	subscriptions: {
		setup ({ dispatch, history }) {
			return history.listen (({ pathname, query }) => {
				if (pathname === '/usersList') {
					const { page, pageSize } = query
					const pageParams = { page, pageSize }
					dispatch ({ type: 'fetch', payload: { pageParams }})
				}
			})
		},
	},
}